<template>
  <div class="excel-container">
    <!-- <div class="header-section">
      <h2>Excel文件处理工具</h2>
      <p class="description">上传.xlsx文件，系统将自动处理并生成新文件</p>
    </div> -->
    
    <div class="upload-section">
      <el-card class="upload-card">
        <el-upload 
          class="upload-demo" 
          drag 
          action="#" 
          multiple 
          ref="upload" 
          :http-request="uploads" 
          :limit="1"
          :on-exceed="handleExceed" 
          accept=".xlsx"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击选择文件</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传.xlsx格式文件，文件大小不超过100MB
            </div>
          </template>
        </el-upload>
      </el-card>
    </div>
    
    <div class="instructions-section">
      <el-card class="instructions-card">
        <h3>使用说明</h3>
        <ul>
          <li>支持.xlsx格式的Excel文件</li>
          <li>文件需包含4个工作表(sheet)</li>
          <li>工作表1必须包含"订单号"、"订单项目"、"计划行"列</li>
          <li>工作表2、3、4必须包含"订单号"、"订单项目"、"计划行"、"核实备注"列</li>
          <li>处理完成后会自动新生成的Excel文件</li>
        </ul>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
//import { reactive } from 'vue'
import { ref } from 'vue'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId, ElNotification, ElMessage } from 'element-plus'

//import { readBinaryFile } from '@tauri-apps/api/fs';
import { save } from '@tauri-apps/plugin-dialog';//open,
import ExcelJS from "exceljs";
//import { upload } from '@tauri-apps/plugin-upload';
//import FileSaver from "file-saver";
const upload = ref<UploadInstance>()
import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
//import { ca } from 'element-plus/es/locales.mjs';

const uploads = async (val: { file: any; }) => {
    const file = val.file;
    if (file) {
        //file.name = file.name.replace(/\s/g, "");
        if (!file.name.endsWith(".xlsx") && !file.name.endsWith(".XLSX")) {
            ElMessage.error("请上传xlsx或.XLSX文件");
            return;
        }
        const arrayBuffer = await file.arrayBuffer();
        if (!arrayBuffer) return;
        fileHandle(arrayBuffer);
    }
}

const handleExceed: UploadProps['onExceed'] = async (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    try {
        if (!file.name.endsWith(".xlsx") && !file.name.endsWith(".XLSX")) {
            ElMessage.error("请上传xlsx或.XLSX文件");
            return;
        }
        const arrayBuffer = await file.arrayBuffer();
        fileHandle(arrayBuffer);
    } catch (error) {

        ElMessage.error('文件解析错误');
    }
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const fileHandle = async (file: ExcelJS.Buffer) => {

    try {


        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(file);

        //三张小表数据map

        const rowDataMap = new Map<string, string>(); // 行号 → 单元格数据数组
        let worksheet2 = workbook.getWorksheet(2);
        let worksheet2_newExceData: Array<Array<string>> = []
        //表2表头
        let worksheet2_newExceHeartColumns: {
            header: string,
            key: string,
            width: number
        }[] = []
        //sheet2订单号列位置
        let worksheet2_rowCount_ddh: number = -1;
        //sheet2订单项目列位置
        let worksheet2_rowCount_ddxm: number = -1;
        //sheet2计划行列位置
        let worksheet2_rowCount_jhh: number = -1;
        //sheet2 核实备注列位置
        let worksheet2_rowCount_hsbz: number = -1;
        const worksheet2_rowDataMap = new Map<number, string>();
        if (worksheet2) {
            worksheet2.eachRow((row: ExcelJS.Row, rowNumber: number) => {
                //console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
                if (rowNumber === 1) {
                    for (let i = 1; i <= row.cellCount; i++) {
                        let commlet = String(row.getCell(i).value).trim();
                        //console.log('commlet:' + commlet + " i:" + i);

                        if (commlet === '订单号') {
                            worksheet2_rowCount_ddh = i;
                        }
                        if (commlet === '订单项目') {
                            worksheet2_rowCount_ddxm = i;
                        }
                        if (commlet === '计划行') {
                            worksheet2_rowCount_jhh = i;
                        }
                        if (commlet === '核实备注') {
                            worksheet2_rowCount_hsbz = i;
                        }
                        if (containsKeywords(commlet)) {
                            worksheet2_rowDataMap.set(i, commlet);
                        }
                        worksheet2_newExceHeartColumns.push({
                            header: commlet,
                            key: commlet,
                            width: 20
                        });
                    }
                } else {
                    let celldata = new Array<string>()
                    let rowCount_ddh_val = String(row.getCell(worksheet2_rowCount_ddh).text).trim();
                    let rowCount_ddxm_val = String(row.getCell(worksheet2_rowCount_ddxm).text).trim();
                    let rowCount_jhh_val = String(row.getCell(worksheet2_rowCount_jhh).text).trim();
                    let rowCount__key_rowDataMap2 = ''
                    for (let j = 1; j <= row.cellCount; j++) {
                        //列值
                        let val_1 = String(row.getCell(j).text).trim();
                        let val = "";
                        if (worksheet2_rowDataMap.has(j)) {
                            val = convertDateIfNeeded(String(row.getCell(j).text).trim());
                        } else {
                            val = val_1;
                        }

                        // if (worksheet2_rowCount_ddh == j) {
                        //     rowCount_ddh_val = val;
                        // }
                        // if (worksheet2_rowCount_ddxm == j) {
                        //     rowCount_ddxm_val = val;
                        // }
                        // if (worksheet2_rowCount_jhh == j) {
                        //     rowCount_jhh_val = val;
                        // }
                        celldata.push(val);
                        if (rowCount_ddh_val != '' && rowCount_ddxm_val != '' && rowCount_jhh_val != '' && worksheet2_rowCount_hsbz == j && rowCount__key_rowDataMap2 === '') {
                            //console.log('表2 例 index:' + j + ' 核实备注: ' + val + "rowCount_ddh_val: " + rowCount_ddh_val + ' rowCount_ddxm_val: ' + rowCount_ddxm_val + ' rowCount_jhh_val: ' + rowCount_jhh_val);
                            rowCount__key_rowDataMap2 = rowCount_ddh_val + "_" + rowCount_ddxm_val + "_" + rowCount_jhh_val
                            rowDataMap.set(rowCount__key_rowDataMap2, convertDateIfNeeded(val));
                        }
                    }
                    worksheet2_newExceData.push(celldata);
                }
                if (worksheet2_rowCount_ddh < 0 || worksheet2_rowCount_ddxm < 0 || worksheet2_rowCount_jhh < 0 || worksheet2_rowCount_hsbz < 0) {
                    ElMessage.error('工作簿表2中订单号、订单项、计划号、核实备注列不完整!');
                    return;
                }
            });
        } else {
            ElMessage.error('工作簿中未找到工作表2');
            return;
        }
        //console.log('表2数据: worksheet2_rowCount_ddh: ' + worksheet2_rowCount_ddh + ' worksheet2_rowCount_ddxm: ' + worksheet2_rowCount_ddxm + ' worksheet2_rowCount_jhh: ' + worksheet2_rowCount_jhh + ' worksheet2_rowCount_hsbz: ' + worksheet2_rowCount_hsbz);
        //console.log('表2数据: worksheet2_newExceData: ' + worksheet2_newExceHeartColumns.toString);
        let worksheet3 = workbook.getWorksheet(3);
        let worksheet3_newExceData: Array<Array<string>> = []
        //表2表头
        let worksheet3_newExceHeartColumns: {
            header: string,
            key: string,
            width: number
        }[] = []
        //sheet2订单号列位置
        let worksheet3_rowCount_ddh: number = -1;
        //sheet2订单项目列位置
        let worksheet3_rowCount_ddxm: number = -1;
        //sheet2计划行列位置
        let worksheet3_rowCount_jhh: number = -1;
        //sheet2 核实备注列位置
        let worksheet3_rowCount_hsbz: number = -1;
        let worksheet3_rowDataMap = new Map<number, string>();
        if (worksheet3) {
            worksheet3.eachRow((row: ExcelJS.Row, rowNumber: number) => {
                //console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
                //console.log(' Row ' + rowNumber + 'cellCount: ' + row.cellCount + ' Cell(1) = ' + row.getCell(1));
                if (rowNumber === 1) {
                    for (let i = 1; i <= row.cellCount; i++) {
                        let commlet = String(row.getCell(i).value).trim();
                        if (commlet === '订单号') {
                            worksheet3_rowCount_ddh = i;
                        }
                        if (commlet === '订单项目') {
                            worksheet3_rowCount_ddxm = i;
                        }
                        if (commlet === '计划行') {
                            worksheet3_rowCount_jhh = i;
                        }
                        if (commlet === '核实备注') {
                            worksheet3_rowCount_hsbz = i;
                        }
                        if (containsKeywords(commlet)) {
                            worksheet3_rowDataMap.set(i, commlet);
                        }
                        worksheet3_newExceHeartColumns.push({
                            header: commlet,
                            key: commlet,
                            width: 20
                        });
                    }
                } else {
                    let celldata = new Array<string>()
                    let rowCount_ddh_val = String(row.getCell(worksheet3_rowCount_ddh).text).trim();
                    let rowCount_ddxm_val = String(row.getCell(worksheet3_rowCount_ddxm).text).trim();
                    let rowCount_jhh_val = String(row.getCell(worksheet3_rowCount_jhh).text).trim();
                    let rowCount__key_rowDataMap3 = '';
                    for (let i = 1; i <= row.cellCount; i++) {
                        //列值
                        let val_1 = String(row.getCell(i).text).trim();
                        let val = "";
                        if (worksheet3_rowDataMap.has(i)) {
                            val = convertDateIfNeeded(String(row.getCell(i).text).trim());
                        } else {
                            val = val_1;
                        }
                        // if (worksheet3_rowCount_ddh == i) {
                        //     rowCount_ddh_val = val;
                        // }
                        // if (worksheet3_rowCount_ddxm == i) {
                        //     rowCount_ddxm_val = val;
                        // }
                        // if (worksheet3_rowCount_jhh == i) {
                        //     rowCount_jhh_val = val;
                        // }
                        celldata.push(val);
                        if (rowCount_ddh_val != '' && rowCount_ddxm_val != '' && rowCount_jhh_val != '' && worksheet3_rowCount_hsbz == i && rowCount__key_rowDataMap3 === '') {
                            rowCount__key_rowDataMap3 = rowCount_ddh_val + "_" + rowCount_ddxm_val + "_" + rowCount_jhh_val
                            rowDataMap.set(rowCount__key_rowDataMap3, convertDateIfNeeded(val));
                        }

                    }
                    worksheet3_newExceData.push(celldata);
                }

            });
            if (worksheet3_rowCount_ddh < 0 || worksheet3_rowCount_ddxm < 0 || worksheet3_rowCount_jhh < 0 || worksheet3_rowCount_hsbz < 0) {
                ElMessage.error('工作簿表3中订单号、订单项、计划号、核实备注列不完整!');
                return;
            }
        } else {
            ElMessage.error('工作簿中未找到工作表3');
            return;
        }


        let worksheet4 = workbook.getWorksheet(4);
        let worksheet4_newExceData: Array<Array<string>> = []
        //表2表头
        let worksheet4_newExceHeartColumns: {
            header: string,
            key: string,
            width: number
        }[] = []
        //sheet2订单号列位置
        let worksheet4_rowCount_ddh: number = -1;
        //sheet2订单项目列位置
        let worksheet4_rowCount_ddxm: number = -1;
        //sheet2计划行列位置
        let worksheet4_rowCount_jhh: number = -1;
        //sheet2 核实备注列位置
        let worksheet4_rowCount_hsbz: number = -1;
        let worksheet4_rowDataMap = new Map<number, string>();
        if (worksheet4) {
            worksheet4.eachRow((row: ExcelJS.Row, rowNumber: number) => {
                //console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
                //console.log(' Row ' + rowNumber + 'cellCount: ' + row.cellCount + ' Cell(1) = ' + row.getCell(1));
                if (rowNumber === 1) {
                    for (let i = 1; i <= row.cellCount; i++) {
                        let commlet = String(row.getCell(i).value).trim();
                        if (commlet === '订单号') {
                            worksheet4_rowCount_ddh = i;
                        }
                        if (commlet === '订单项目') {
                            worksheet4_rowCount_ddxm = i;
                        }
                        if (commlet === '计划行') {
                            worksheet4_rowCount_jhh = i;
                        }
                        if (commlet === '核实备注') {
                            worksheet4_rowCount_hsbz = i;
                        }
                        //判断时间列
                        if (containsKeywords(commlet)) {
                            worksheet4_rowDataMap.set(i, commlet);
                        }
                        worksheet4_newExceHeartColumns.push({
                            header: commlet,
                            key: commlet,
                            width: 20
                        });
                    }
                } else {
                    let celldata = new Array<string>()
                    let rowCount_ddh_val = String(row.getCell(worksheet4_rowCount_ddh).text).trim();
                    let rowCount_ddxm_val = String(row.getCell(worksheet4_rowCount_ddxm).text).trim();
                    let rowCount_jhh_val = String(row.getCell(worksheet4_rowCount_jhh).text).trim();;
                    let rowCount__key_rowDataMap4 = '';
                    for (let i = 1; i <= row.cellCount; i++) {
                        //列值
                        let val_1 = String(row.getCell(i).text).trim();
                        let val = "";
                        if (worksheet4_rowDataMap.has(i)) {
                            val = convertDateIfNeeded(String(row.getCell(i).text).trim());
                        } else {
                            val = val_1;
                        }
                        // if (worksheet4_rowCount_ddh == i) {
                        //     rowCount_ddh_val = val;
                        // }
                        // if (worksheet4_rowCount_ddxm == i) {
                        //     rowCount_ddxm_val = val;
                        // }
                        // if (worksheet4_rowCount_jhh == i) {
                        //     rowCount_jhh_val = val;
                        // }
                        celldata.push(val);
                        if (rowCount_ddh_val != '' && rowCount_ddxm_val != '' && rowCount_jhh_val != '' && worksheet4_rowCount_hsbz == i && rowCount__key_rowDataMap4 === '') {
                            rowCount__key_rowDataMap4 = rowCount_ddh_val + "_" + rowCount_ddxm_val + "_" + rowCount_jhh_val
                            rowDataMap.set(rowCount__key_rowDataMap4, convertDateIfNeeded(val));
                        }
                    }
                    worksheet4_newExceData.push(celldata);
                }

            });
            if (worksheet4_rowCount_ddh < 0 || worksheet4_rowCount_ddxm < 0 || worksheet4_rowCount_jhh < 0 || worksheet4_rowCount_hsbz < 0) {
                ElMessage.error('工作簿表4中订单号、订单项、计划号、核实备注列不完整!');
                return;
            }
        } else {
            ElMessage.error('工作簿中未找到工作表4');
            return;
        }


        let worksheet1 = workbook.getWorksheet(1);
        let worksheet1_newExceData: Array<Array<string>> = []
        //表1表头
        let worksheet1_newExceHeartColumns: {
            header: string,
            key: string,
            width: number
        }[] = []
        //sheet1订单号列位置
        let worksheet1_rowCount_ddh: number = -1;
        //sheet1订单项目列位置
        let worksheet1_rowCount_ddxm: number = -1;
        //sheet1计划行列位置
        let worksheet1_rowCount_jhh: number = -1;
        //计划行欠出货单只装数量列 位置
        let worksheet1_rowCount_jhhqdsl: number = -1;
        let worksheet1_rowDataMap = new Map<number, string>();
        if (worksheet1) {
            worksheet1.eachRow((row: ExcelJS.Row, rowNumber: number) => {
                //console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
                //console.log(' Row ' + rowNumber + 'cellCount: ' + row.cellCount + ' Cell(1) = ' + row.getCell(1));
                //表头
                if (rowNumber === 1) {
                    for (let i = 1; i <= row.cellCount; i++) {
                        let commlet = String(row.getCell(i).text).trim();
                        if (commlet === '订单号') {
                            worksheet1_rowCount_ddh = i;
                        }
                        if (commlet === '订单项目') {
                            worksheet1_rowCount_ddxm = i;
                        }
                        if (commlet === '计划行') {
                            worksheet1_rowCount_jhh = i;
                        }
                        if (containsKeywords(commlet)) {
                            worksheet1_rowDataMap.set(i, commlet);
                        }
                        worksheet1_newExceHeartColumns.push({
                            header: commlet,
                            key: commlet,
                            width: 20
                        });
                        if (commlet === '计划行欠出货单只装数量') {
                            worksheet1_rowCount_jhhqdsl = i;
                            worksheet1_newExceHeartColumns.push({
                                header: "日期",
                                key: "日期",
                                width: 20
                            });
                            worksheet1_newExceHeartColumns.push({
                                header: "原因备注",
                                key: "原因备注",
                                width: 20
                            });
                        }
                    }
                } else {
                    //数据处理
                    let celldata = new Array<string>()
                    let rowCount_ddh_val = String(row.getCell(worksheet1_rowCount_ddh).text).trim();
                    let rowCount_ddxm_val = String(row.getCell(worksheet1_rowCount_ddxm).text).trim();;
                    let rowCount_jhh_val = String(row.getCell(worksheet1_rowCount_jhh).text).trim();;
                    for (let i = 1; i <= row.cellCount; i++) {
                        //列值
                        //列值
                        let val_1 = String(row.getCell(i).text).trim();
                        if (worksheet1_rowDataMap.has(i)) {
                            val_1 = convertDateIfNeeded(String(row.getCell(i).text).trim());
                        }
                        //加入两列
                        celldata.push(val_1);
                        if (worksheet1_rowCount_jhhqdsl == i && rowCount_ddh_val != '' && rowCount_ddxm_val != '' && rowCount_jhh_val != '') {
                            let code_key = rowCount_ddh_val + "_" + rowCount_ddxm_val + "_" + rowCount_jhh_val;
                            //获取
                            let val = rowDataMap.get(code_key);
                            //console.log('code_key: ' + code_key + ' val: ' + val);
                            if (val != null && val != '') {
                                let val_c = splitAtLastChineseChar(val);
                                celldata.push(val_c[1]);
                                celldata.push(val_c[0]);

                            } else {
                                celldata.push("###");
                                celldata.push("###");
                            }
                        }
                    }
                    worksheet1_newExceData.push(celldata);
                }

            });

            if (worksheet1_rowCount_jhhqdsl < 0) {
                ElMessage.error('工作簿表1中“计划行欠出货单只装数量”列未找到!');
                return;
            }
            if (worksheet1_rowCount_ddh < 0 || worksheet1_rowCount_ddxm < 0 || worksheet1_rowCount_jhh < 0) {
                ElMessage.error('工作簿表1中订单号、订单项、计划号列不完整!');
                return;
            }
        } else {
            ElMessage.error('工作簿中未找到工作表1');
            return;
        }
        const workbook_output = new ExcelJS.Workbook(); // 创建新的工作簿
        const worksheet_output_sheet1 = workbook_output.addWorksheet('新表'); // 创建新的工作表
        worksheet_output_sheet1.columns = worksheet1_newExceHeartColumns;
        for (let i = 0; i < worksheet1_newExceData.length; i++) {
            worksheet_output_sheet1.addRow(worksheet1_newExceData[i]);
        }
        const worksheet_output_sheet2 = workbook_output.addWorksheet('全新'); // 创建新的工作表
        worksheet_output_sheet2.columns = worksheet2_newExceHeartColumns;
        for (let i = 0; i < worksheet2_newExceData.length; i++) {
            worksheet_output_sheet2.addRow(worksheet2_newExceData[i]);
        }
        const worksheet_output_sheet3 = workbook_output.addWorksheet('回收'); // 创建新的工作表
        worksheet_output_sheet3.columns = worksheet3_newExceHeartColumns;
        for (let i = 0; i < worksheet3_newExceData.length; i++) {
            worksheet_output_sheet3.addRow(worksheet3_newExceData[i]);
        }
        const worksheet_output_sheet4 = workbook_output.addWorksheet('复印机'); // 创建新的工作表
        worksheet_output_sheet4.columns = worksheet4_newExceHeartColumns;
        for (let i = 0; i < worksheet4_newExceData.length; i++) {
            worksheet_output_sheet4.addRow(worksheet4_newExceData[i]);
        }
        //await workbook.xlsx.writeFile("哈哈哈哈.xlsx");
        const path: string | null = await save({
            title: `保存文件`,
            filters: [
                {
                    name: 'My Filter',
                    extensions: ['xlsx'],
                },
            ],
        });
        if (!path) {
            ElMessage.info('用户取消了保存操作');
            return;
        }

        const imageArrayBuffer = await workbook_output.xlsx.writeBuffer();
        //const imageArrayBuffer = await imageBlob.arrayBuffer();
        //const contents = new Uint8Array(); // fill a byte array
        const contents = new Uint8Array(imageArrayBuffer);

        await writeFile(path, contents, {
            baseDir: BaseDirectory.Download,
        });
        success_ElNotification('', '处理成功');
        // 导出表格文件
        // workbook_output.xlsx.writeBuffer().then((buffer) => {
        //     let file = new Blob([buffer], { type: "application/octet-stream" });
        //     FileSaver.saveAs(file, path);
        // }).catch(error => {
        //     ElMessage.info('保存失败: ' + error);
        //     //console.log('Error writing excel export', error)
        // })
    } catch (error) {
        ElMessage.error('处理错误: ' + error);
    };
}
/**
 * 判断字符串是否包含中文，并在最后一个中文字符处拆分
 * @param input 要处理的字符串
 * @returns [前半部分, 后半部分] 的元组。若无中文则返回 [原字符串, ""]；
 *          若为纯中文则返回 [原字符串, "#"]
 */
function splitAtLastChineseChar(input: string): [string, string] {
    // 扩展中文范围：基本汉字、扩展A区、扩展B区、兼容汉字、繁体字等
    const chineseRegex = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u{20000}-\u{2a6df}\u{2a700}-\u{2b73f}\u{2b740}-\u{2b81f}]/u;
    if (isDate(input)) {
        return ["", input];
    }
    // 检查是否纯中文
    let isPureChinese = true;
    for (const char of input) {
        if (!chineseRegex.test(char)) {
            isPureChinese = false;
            break;
        }
    }
    if (isPureChinese) {
        return [input, "2030/01/01"];
    }

    // 查找最后一个中文字符的位置
    let lastIndex = -1;
    for (let i = input.length - 1; i >= 0; i--) {
        if (chineseRegex.test(input[i])) {
            lastIndex = i;
            break;
        }
    }

    // 根据是否找到中文字符进行拆分
    if (lastIndex !== -1) {
        let text = input.substring(0, lastIndex + 1); // 包含最后一个中文字符
        let data = normalizeDateString(input.substring(lastIndex + 1))
        return [
            text,
            data   // 剩余部分
        ];
    }
    return [input, "2030/01/01"];
}

/**
 * 判断字符串是否为日期格式，如果是则转换为YYYY-MM-DD格式
 * @param input 要检测的字符串
 * @returns 转换后的日期字符串或原字符串
 */
function convertDateIfNeeded(input: string): string {
    // 尝试解析为日期对象
    const date = new Date(input);

    // 检查解析结果是否有效
    if (!isNaN(date.getTime())) {
        // 提取日期组件并格式化为YYYY-MM-DD
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}/${month}/${day}`;
    }

    // 不是有效日期则返回原字符串
    return input;
}
function isDate(input: string): boolean {
    // 尝试解析为日期对象
    const date = new Date(input);
    return !isNaN(date.getTime())
}

/**
 * 判断字符串是否包含"交期"或"日期"关键词
 * @param input 要检测的字符串
 * @returns 如果包含关键词返回true，否则返回false
 */
function containsKeywords(input: string): boolean {
    return input.includes("交期") || input.includes("日期") || input.includes("核实备注");
}

/**
 * 规范化日期字符串，支持多种格式：
 * - "7/8" → 转换为当前年份的"YYYY/MM/DD"格式
 * - "2025/7/8" → 转换为"YYYY/MM/DD"格式
 * - "7-8" → 转换为当前年份的"YYYY/MM/DD"格式
 * - "2025-7-8" → 转换为"YYYY/MM/DD"格式
 * @param input 要转换的日期字符串
 * @returns 转换后的标准日期字符串
 */
function normalizeDateString(input: string): string {
    if (input === "") {
        return "2030/01/01";
    }
    // 尝试匹配 "月/日" 格式（如 "7/8"）
    const monthDayMatch = input.match(/^(\d{1,2})\/(\d{1,2})$/);
    if (monthDayMatch) {
        const currentYear = new Date().getFullYear();
        const month = String(parseInt(monthDayMatch[1])).padStart(2, '0');
        const day = String(parseInt(monthDayMatch[2])).padStart(2, '0');
        return `${currentYear}/${month}/${day}`;
    }

    // 尝试匹配 "年/月/日" 格式（如 "2025/7/8"）
    const yearMonthDayMatch = input.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);
    if (yearMonthDayMatch) {
        const year = yearMonthDayMatch[1];
        const month = String(parseInt(yearMonthDayMatch[2])).padStart(2, '0');
        const day = String(parseInt(yearMonthDayMatch[3])).padStart(2, '0');
        return `${year}/${month}/${day}`;
    }

    // 尝试匹配 "月-日" 格式（如 "7-8"）
    const monthDayDashMatch = input.match(/^(\d{1,2})-(\d{1,2})$/);
    if (monthDayDashMatch) {
        const currentYear = new Date().getFullYear();
        const month = String(parseInt(monthDayDashMatch[1])).padStart(2, '0');
        const day = String(parseInt(monthDayDashMatch[2])).padStart(2, '0');
        return `${currentYear}/${month}/${day}`;
    }

    // 尝试匹配 "年-月-日" 格式（如 "2025-7-8"）
    const yearMonthDayDashMatch = input.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
    if (yearMonthDayDashMatch) {
        const year = yearMonthDayDashMatch[1];
        const month = String(parseInt(yearMonthDayDashMatch[2])).padStart(2, '0');
        const day = String(parseInt(yearMonthDayDashMatch[3])).padStart(2, '0');
        return `${year}/${month}/${day}`;
    }

    // 无法识别的格式返回原字符串
    return input;
}

const success_ElNotification = (title: string, message: string) => {
    ElNotification({
        title: title === "" ? "Success" : title,
        message: message,
        type: 'success',
    })
}


const below20 = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
    "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];

function numberToWords(num: number): string {
    if (num === 0) return "zero";

    function convertHundreds(n: number): string {
        if (n < 20) return below20[n];
        if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? "-" + below20[n % 10] : "");
        return below20[Math.floor(n / 100)] + " hundred" + (n % 100 ? " and " + convertHundreds(n % 100) : "");
    }

    let result = "";
    const billion = Math.floor(num / 1000000000);
    num %= 1000000000;
    const million = Math.floor(num / 1000000);
    num %= 1000000;
    const thousand = Math.floor(num / 1000);
    num %= 1000;

    if (billion) result += convertHundreds(billion) + " billion ";
    if (million) result += convertHundreds(million) + " million ";
    if (thousand) result += convertHundreds(thousand) + " thousand ";
    if (num) result += convertHundreds(num);

    return result.trim();
}

// 使用示例
console.log(numberToWords(123));
// 输出: "one hundred and twenty-three"
console.log(numberToWords(4567));
// 输出: "four thousand five hundred and sixty-seven"
</script>

<style scoped>
.excel-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0px;
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
}

.header-section h2 {
  color: #303133;
  margin-bottom: 10px;
}

.description {
  color: #606266;
  font-size: 14px;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.upload-demo) {
  display: flex;
  justify-content: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  max-width: 500px;
  padding: 40px 20px;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
}

.instructions-section {
  margin-bottom: 30px;
}

.instructions-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.instructions-card h3 {
  color: #303133;
  margin-bottom: 15px;
}

.instructions-card ul {
  padding-left: 20px;
}

.instructions-card li {
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .excel-container {
    padding: 10px;
  }
  
  :deep(.el-upload-dragger) {
    padding: 20px 10px;
  }
}
</style>